const api = require('./api.js')


/**
 * 判断code是否过期
 */
function checkSession() {
	return new Promise(function(resolve, reject) {
		uni.checkSession({
			success: res => {
				resolve(true)
			},
			fail: err => {
				reject(false)
			}
		})
	})

}


/**
 * 获取code
 */
function getCode() {
	return new Promise(function(resolve, reject) {
		uni.login({
			provider: 'weixin',
			success: res => {
				resolve(res.code)
			},
			fail: err => {
				reject(err)
			}
		})
	})
}

/**
 *  初始化登录
 */

function initlogin(){
	return new Promise(function(resolve, reject) {
		uni.login({
			provider: 'weixin',
			success: res => {
				request(api.initlogin,{
					code:res.code
				},'POST').then(res=>{
					resolve(res)
				})
				
			},
			fail: err => {
				reject(err)
			}
		})
	})
}

/**
 * Promise封装微信登录
 */
function login(info) {

	return new Promise(async function(resolve, reject) {

		// 获取code
		let code = await getCode()

		// 判断code是否过期
		const bol = await checkSession()

		// code过期
		if (!bol) {
			code = await getCode()
		}


		const {
			avatarUrl,
			nickName,
			city,
			gender,
			province
		} = info
		// 存入全局
		getApp().globalData.userinfo = info

		// 调用登录接口 向后台发送请求
		request(api.login, {
			code,
			nickname: nickName,
			gender,
			province,
			avatarurl: avatarUrl,
			city,
			pid: getApp().globalData.pid
		}, 'POST').then(res => {
			if (res.data.code == 200) {
				uni.setStorageSync('token', res.data.data)
				resolve(true)
			} else {
				uni.showToast({
					title: '登录失败',
					duration: 2000,
					icon: 'none'
				})
				reject(false)
			}
		})


	})

}


/**
 * Promise封装微信请求
 */
function request(url, data = {}, method = "GET") {

	return new Promise(function(resolve, reject) {
		uni.request({
			url: url,
			data: data,
			method: method,
			header: {
				'Content-Type': 'application/json',
				'Token': uni.getStorageSync('token')
			},
			success: function(res) {
				resolve(res)
			},
			fail: function(err) {
				reject(err)
			}
		})
	})
}


export default {
	request,
	login,
	initlogin
}
